package com.arpa.wms.controller;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.dto.InventoryStatusDTO;
import com.arpa.wms.domain.entity.InventoryStatus;
import com.arpa.wms.domain.enums.StatusEnum;
import com.arpa.wms.domain.vo.InventoryStatusVO;
import com.arpa.wms.domain.vo.WarehouseVO;
import com.arpa.wms.service.IInventoryService;
import com.arpa.wms.service.IInventoryStatusService;
import com.arpa.wms.service.IReceiveRegisterService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.testng.collections.Lists;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * <p>
 * 库存状态 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-08-03
 */
@Api(tags = "库存状态")
@RestController
@RequestMapping(value="/inventoryStatus", produces = "application/json;charset=UTF-8")
@Log4j2
public class InventoryStatusController  {

   @Autowired
   private IInventoryStatusService  iInventoryStatusService;

   @Autowired
   private IReceiveRegisterService iReceiveRegisterService;

   @Autowired
   private IInventoryService iInventoryService;

    /**
     * 获取 库存状态 列表
     *
     * @param inventoryStatusDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 库存状态 列表", notes = "获取 库存状态 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = InventoryStatusVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(InventoryStatusDTO inventoryStatusDTO,HttpServletRequest request) {
        try {
            //校验授权仓库code和货主code不能为空
            Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            //增加机构过滤
            inventoryStatusDTO.setGroupCode(UserUtil.getBranchCode());
            //登录仓库授权的货主过滤
            inventoryStatusDTO.setShipmentCodes(authMap.get(CommonConst.SHIPMENT_CODES));
            InventoryStatusVO inventoryStatusVOSum = iInventoryStatusService.queryListSum(inventoryStatusDTO);
            List<InventoryStatusVO> inventoryStatusVOList = iInventoryStatusService.queryList(inventoryStatusDTO);

            inventoryStatusVOList.forEach(info ->{
                info.getStatus();
                StatusEnum enumByValue = StatusEnum.getEnumByValue(info.getStatus());
                if(null != enumByValue){
                    //启用or停用
                    info.setStatusText(enumByValue.getDesc());
                }
            });
            Page returnPage = new Page(inventoryStatusDTO.getPageNum(),inventoryStatusDTO.getPageSize());
            returnPage.setRecords(inventoryStatusVOList);
            returnPage.setTotal(inventoryStatusVOSum.getTotal());
            returnPage.setSumObject(inventoryStatusVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 库存状态
     *
     * @param entity InventoryStatus
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 库存状态 ", notes = "添加 库存状态 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@Validated(InventoryStatus.Save.class) InventoryStatus entity, HttpServletRequest request) {
        try {
            entity.setGroupCode(UserUtil.getBranchCode());
            iInventoryStatusService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取库存状态详情
    *
    * @param code
    * @param request
    * @return
    */
    @ApiOperation(value = "获取库存状态详情", notes = "获取库存状态详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "库存状态code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = InventoryStatus.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result inventoryStatus(@PathVariable String code,HttpServletRequest request) {
        try {
            InventoryStatusVO inventoryStatusVO=iInventoryStatusService.getOneByCode(code);
            return Result.ok().data(inventoryStatusVO);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改库存状态
     *
     * @param entity 库存状态
     * @param request
     * @return
     */
    @ApiOperation(value = "修改库存状态", notes = "修改库存状态")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@Validated(InventoryStatus.Update.class) InventoryStatus entity,HttpServletRequest request) {
        if(StrUtil.isBlank(entity.getCode())){
            return Result.error("code不能为空");
        }
        int updateNum = iInventoryStatusService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！code:"+entity.getCode());
        }else{
            return Result.ok("修改成功,更新"+updateNum+"条数据！");
        }
    }

    /**
     * 删除 库存状态
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 库存状态 ", notes = "删除 库存状态 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            Map<String, Object> result = iInventoryStatusService.batchdel(codes);
            Integer success = MapUtil.getInt(result, "success");
            List<String> notDelete = MapUtil.get(result, "notDelete", List.class);
            int failNum = codes.size() - success;
            StringBuilder builder = new StringBuilder();
            builder.append("删除成功" + success + "条；失败" + failNum + "条；");
            if(IterUtil.isNotEmpty(notDelete)){
                for (String m:notDelete) {
                    builder.append("<br><font color='red'>库存状态【"+m+"】删除失败，已被启用过;</font>");
                }
            }
            return Result.ok(builder.toString());
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 启用
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "启用", notes = "启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/active")
    public Result active(@RequestParam List<String> codes, HttpServletRequest request) {
        String groupCode=UserUtil.getBranchCode();
        Map<String, Object> result = iInventoryStatusService.activeStatus(codes, StatusEnum.ACTIVE);
        Integer success = MapUtil.getInt(result, "success");
        int failNum = codes.size() - success;
        return Result.ok("启用成功" + success + "条；失败" + failNum + "条；");
    }

    /**
     * 停用
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "停用", notes = "停用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/unactive")
    public Result unactive(@RequestParam List<String> codes, HttpServletRequest request) {

        String groupCode=UserUtil.getBranchCode();
        Map<String, Object> result = iInventoryStatusService.activeStatus(codes, StatusEnum.UNACTIVE);
        Integer success = MapUtil.getInt(result, "success");
        List<String> receiveUseName = MapUtil.get(result, "receiveUseName", List.class);
        List<String> inventoryUseName = MapUtil.get(result, "inventoryUseName", List.class);
        int failNum = codes.size() - success;
        StringBuilder builder = new StringBuilder();
        builder.append("停用成功" + success + "条；失败" + failNum + "条；");
        if(IterUtil.isNotEmpty(receiveUseName)){
            for (String m:receiveUseName) {
                builder.append("<br><font color='red'>库存状态【"+m+"】停用失败，收货单正在使用中;</font>");
            }
        }
        if(IterUtil.isNotEmpty(inventoryUseName)){
            for (String m:inventoryUseName) {
                builder.append("<br><font color='red'>库存状态【"+m+"】停用失败，库存正在使用中;</font>");
            }
        }
        return Result.ok(builder.toString());

    }


    /**
     * 根据货主获取 库存状态下拉列表
     *
     * @param shipmentCode
     * @param request
     * @return
     */
    @ApiOperation(value = "根据货主获取 库存状态下拉列表", notes = "根据货主获取 库存状态下拉列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "shipmentCode", value = "货主code", paramType = "query", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = WarehouseVO.class))
    @NeedLogin
    @GetMapping("/chooseData")
    public Result chooseData(@RequestParam(defaultValue = "") String shipmentCode, HttpServletRequest request) {
        try {
            List<InventoryStatus> inventoryStatuses = null;
            if(StrUtil.isNotBlank(shipmentCode)) {
                // XYTODO TODO 下一步可以使用缓存，根据货主code过滤信息
                inventoryStatuses = iInventoryStatusService.list(new QueryWrapper<InventoryStatus>().lambda()
                        .eq(InventoryStatus::getDeleted, "0").eq(InventoryStatus::getStatus, StatusEnum.ACTIVE.getValue())
                        .eq(InventoryStatus::getShipmentCode, shipmentCode).eq(InventoryStatus::getGroupCode,UserUtil.getBranchCode()));
            }
            return Result.ok().data(inventoryStatuses);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据货主获取 库存状态下拉列表
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "根据货主获取 库存状态下拉列表", notes = "根据货主获取 库存状态下拉列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = WarehouseVO.class))
    @NeedLogin
    @GetMapping("/chooseDataByAuthShipment")
    public Result chooseData(HttpServletRequest request) {
        try {
            //校验授权仓库code和货主code不能为空
            Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            List<String> shipmentCodes = authMap.get(CommonConst.SHIPMENT_CODES);
            List<InventoryStatus> inventoryStatuses ;
            inventoryStatuses = iInventoryStatusService.list(new QueryWrapper<InventoryStatus>().lambda()
                    .eq(InventoryStatus::getDeleted, "0").eq(InventoryStatus::getStatus, StatusEnum.ACTIVE.getValue())
                    .in(InventoryStatus::getShipmentCode, shipmentCodes));
            Set<String> goodsStatusNames = inventoryStatuses.stream().map(e -> e.getName()).collect(Collectors.toSet());
            return Result.ok().data(goodsStatusNames);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }
}
